/**
 * Package:com.goldcitynet.robot;
 * $Id: MainUI.java,v 1.2 2009/03/25 09:48:26 zhangpei Exp $
 * Copyright(c) 2001-2005 www.afteryuan.com
 */
package com.afteryuan.robot;

import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

/**
 * MainUI
 * <p/>
 * <p><a href="MainUI.java.html"><i>View Source</i></a></p>
 *
 * @author <a href="mailto:afteryuan@afteryuan.com">$Author: zhangpei $</a>
 * @version $Revision: 1.2 $
 */
public class MainUI {
    private static Log log = LogFactory.getLog(MainUI.class);
    private JPanel mainPanel;
    private JTextField numberStart;
    private JTextField frozenMin;
    private JTextField frozenMax;
    private JTextField loaderField;
    private JButton importButton;
    private JPanel formPanel;
    private JButton start;
    private JPanel detailPanel;
    private JPanel statisticPanel;
    private JPanel LogPanel;
    private JTextPane logTextPanel;
    private JComboBox sceneBox;
    private JComboBox number;
    private JLabel numberLabel;
    private JLabel totalLabal;
    private JLabel timeLabel;
    private JLabel averageTimeLabel;
    private JLabel maxTimeLabel;
    private JLabel minTimeLabel;
    private JLabel mostTimeLabel;
    final private MainModel mainModel = MainModel.getInstance();
    public Logout logout;
    public List<Thread> robots = new ArrayList<Thread>();

    public MainUI() {
        mainModel.setMain(this);
        logTextPanel.setEditable(false);
        logTextPanel.setText("ready!");
        frozenMin.setText("1");
        frozenMax.setText("10");
        numberStart.setText("1000");
        number.addItem("数量");
        number.addItem("1");
        number.addItem("5");
        number.addItem("10");
        number.addItem("20");
        number.addItem("50");
        number.addItem("100");
        logout = new Logout(logTextPanel);
        Map<String,String>scenes =  mainModel.getScenes();
        sceneBox.addItem("选择场景");
        for(Map.Entry<String,String> entry : scenes.entrySet()){
            sceneBox.addItem(entry.getValue());
        }
        sceneBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange()==ItemEvent.SELECTED){
//                     JOptionPane.showConfirmDialog(null,e.getItem());
                     mainModel.setSceneName((String)e.getItem());
                }
            }
        });

        number.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange()==ItemEvent.SELECTED){
//                     JOptionPane.showConfirmDialog(null,e.getItem());
                     mainModel.setNumber(Integer.parseInt((String)e.getItem()));
                }
            }
        });

        start.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(e.getActionCommand().equals("开始"))startAction(e);
                if(e.getActionCommand().equals("停止"))stopAction(e);
            }
        });
    }

    private void stopAction(ActionEvent e) {
        start.setText("开始");
        numberStart.setEnabled(true);
        frozenMax.setEnabled(true);
        frozenMin.setEnabled(true);
        sceneBox.setEnabled(true);
        number.setEnabled(true);
        stopRobot();
    }

    /*点击开始*/
    private void startAction(ActionEvent e) {                                          
        if(numberStart.getText().equals("")){
            JOptionPane.showConfirmDialog(null,"开始数字无效","输入错误",JOptionPane.CANCEL_OPTION);
            return;
        }
        log.debug(sceneBox.getItemAt(sceneBox.getSelectedIndex()).toString());
        if(sceneBox.getItemAt(sceneBox.getSelectedIndex()).toString().equals("选择场景")){
            JOptionPane.showConfirmDialog(null,"请选择场景","输入错误",JOptionPane.CANCEL_OPTION);
            return;
        }
        if(number.getItemAt(number.getSelectedIndex()).toString().equals("数量")){
            JOptionPane.showConfirmDialog(null,"请选择数量","输入错误",JOptionPane.CANCEL_OPTION);
            return;
        }

        /************ 验证完成 ************/
        start.setText("停止");
        numberStart.setEnabled(false);
        frozenMax.setEnabled(false);
        frozenMin.setEnabled(false);
        sceneBox.setEnabled(false);
        number.setEnabled(false);


        mainModel.setNumberStart(Integer.parseInt(numberStart.getText()));
        mainModel.setFrozenMax(Integer.parseInt(frozenMax.getText()));
        mainModel.setFrozenMin(Integer.parseInt(frozenMin.getText()));
        logout.appendLog("start threads ...");
        startRobot();
    }

   private void stopRobot() {
        try {
            for(Thread r:robots){
                r.interrupt();
            }
            robots.clear();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logout.appendLog("removed all the robots");

    }
   private void startRobot() {
        try {
            for(int i=mainModel.getNumberStart();i<mainModel.getNumberStart()+mainModel.getNumber();i++){
                Robot r =new Robot(mainModel.getSceneId(),mainModel.getSceneId(), String.valueOf(i),"sockethost",10088);
                r.setLogout(logout);
                robots.add(r);
                r.start();
                Thread.sleep(500);
//            String batfile = "java -jar D:\\Project\\goldcity_robot\\release\\goldcity_robot.jar "+mainModel.getSceneId()+" "+i+" "+"server118"+" "+"10086";
//                log.debug(batfile);
//                logTextPanel.setText(logTextPanel.getText()+"\n"+"robot "+i+" starting!");
//                RobotProcess rp = new RobotProcess();
//                rp.process =  Runtime.getRuntime().exec(batfile);
//                rp.reader = new BufferedReader(new InputStreamReader(rp.process.getInputStream()));
//                mainModel.getProcesses().put(String.valueOf(i),rp);

//                if (rp.process.waitFor() == 0){
//                    rp.reader = new BufferedReader(new InputStreamReader(rp.process.getInputStream()));
//                    mainModel.getProcesses().put(String.valueOf(i),rp);
//                }else{
//                    log.debug(i+" start failed");
//                    logTextPanel.setText(logTextPanel.getText()+"\n"+"robot "+i+" failed!");
//                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public void updateStatPanel(){
        totalLabal.setText(String.valueOf(mainModel.getTotal()));
        timeLabel.setText(String.valueOf(mainModel.getTotalTime()));
        averageTimeLabel.setText(String.valueOf(mainModel.getAverageTime()));
        maxTimeLabel.setText(String.valueOf(mainModel.getMaxTime()));
        minTimeLabel.setText(String.valueOf(mainModel.getMinTime()));
        mostTimeLabel.setText(String.valueOf(mainModel.getMostTime()));
    }


    public static void main(String[] args) {
        MainUI main = new MainUI();
        final JFrame frame = new JFrame("机器人管理器");
        try {
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
        SwingUtilities.updateComponentTreeUI(frame.getContentPane());
        SwingUtilities.updateComponentTreeUI(main.mainPanel);

        frame.setContentPane(main.mainPanel);
        main.initMenu(frame);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private void initMenu(JFrame frame) {
        JMenuBar jMenuBar = new JMenuBar();
        JMenu fileMenu = new JMenu();
        JMenuItem exitMenuItem = new JMenuItem();
        JMenuItem preferenceMenuItem = new JMenuItem();

        //初始化系统菜单
        fileMenu.setText("File");
        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitItemActionPerformed(evt);
            }

            private void exitItemActionPerformed(ActionEvent evt) {

                System.exit(0);
            }
        });

        fileMenu.add(exitMenuItem);
        preferenceMenuItem.setText("Preference");
        preferenceMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                preferenceItemActionPerformed(evt);
            }

            private void preferenceItemActionPerformed(ActionEvent evt) {
                /* set preference handle here*/
            }
        });
        fileMenu.add(preferenceMenuItem);
        fileMenu.add(exitMenuItem);
        jMenuBar.add(fileMenu);
        frame.setJMenuBar(jMenuBar);
    }
}
